{% extends "base.html" %}

{% block title %}教师仪表盘 - IT课程数据分析系统{% endblock %}

{% block extra_css %}
<style>
    .dashboard-header {
        margin-bottom: 2rem;
    }
    
    .courses-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .course-card {
        background: white;
        border-radius: 8px;
        padding: 1.5rem;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        cursor: pointer;
        transition: all 0.3s;
        border-left: 4px solid #3498db;
    }
    
    .course-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 6px 16px rgba(0,0,0,0.15);
    }
    
    .course-card h3 {
        color: #2c3e50;
        margin-bottom: 0.5rem;
    }
    
    .course-code {
        color: #7f8c8d;
        font-size: 0.9rem;
        margin-bottom: 1rem;
    }
    
    .course-stats {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 1rem;
    }
    
    .stat-item {
        background: #f8f9fa;
        padding: 0.75rem;
        border-radius: 4px;
        text-align: center;
    }
    
    .stat-item .label {
        font-size: 0.8rem;
        color: #7f8c8d;
        margin-bottom: 0.25rem;
    }
    
    .stat-item .value {
        font-size: 1.5rem;
        font-weight: 700;
        color: #2c3e50;
    }
    
    .stat-item.success .value {
        color: #27ae60;
    }
    
    .stat-item.danger .value {
        color: #e74c3c;
    }
    
    .chart-container {
        height: 400px;
        width: 100%;
    }
    
    .students-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 1rem;
    }
    
    .students-table th,
    .students-table td {
        padding: 0.75rem;
        text-align: left;
        border-bottom: 1px solid #e0e0e0;
    }
    
    .students-table th {
        background: #f8f9fa;
        font-weight: 600;
        color: #2c3e50;
    }
    
    .students-table tr:hover {
        background: #f8f9fa;
    }
    
    .badge {
        display: inline-block;
        padding: 0.25rem 0.75rem;
        border-radius: 12px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    
    .badge-success {
        background: #d4edda;
        color: #155724;
    }
    
    .badge-warning {
        background: #fff3cd;
        color: #856404;
    }
    
    .badge-danger {
        background: #f8d7da;
        color: #721c24;
    }
</style>
{% endblock %}

{% block content %}
<div class="dashboard-header">
    <h2>教师仪表盘</h2>
    <p style="color:#7f8c8d;margin-top:0.5rem;">欢迎回来！以下是您所授课程的概览</p>
</div>

<div id="loading" class="loading">
    <div class="spinner"></div>
    <p>加载中...</p>
</div>

<div id="dashboard-content" style="display:none;">
    <h3 style="margin-bottom:1rem;">我的课程</h3>
    <div id="courses-grid" class="courses-grid"></div>
    
    <!-- 选中课程的详细信息 -->
    <div id="course-details" style="display:none;">
        <!-- 风险学生预警（紧凑显示） -->
        <div class="card" id="risk-students-card" style="display:none;">
            <div class="card-title" style="color:#e74c3c;">
                ⚠️ 需要关注的学生 (<span id="risk-count">0</span>人)
                <button onclick="toggleRiskDetails()" style="float:right;padding:0.25rem 0.75rem;background:#e74c3c;color:white;border:none;border-radius:4px;cursor:pointer;font-size:0.85rem;" id="toggle-risk-btn">展开</button>
            </div>
            <div id="risk-students-summary" style="padding:0.75rem;background:#fff3cd;border-radius:4px;margin-top:0.5rem;">
                <!-- 紧凑摘要 -->
            </div>
            <div id="risk-students-details" style="display:none;margin-top:1rem;max-height:200px;overflow-y:auto;">
                <!-- 详细列表 -->
            </div>
        </div>
        
        <!-- 两栏布局 -->
        <div style="display:grid;grid-template-columns:1fr 1fr;gap:1.5rem;">
            <div class="card">
                <div class="card-title">课程成绩分布</div>
                <div id="grade-distribution-chart" style="height:350px;width:100%;"></div>
            </div>
            
            <!-- 出勤率与成绩关联分析 -->
            <div class="card" id="attendance-card" style="display:none;">
                <div class="card-title">出勤率与成绩关联</div>
                <div id="attendance-chart" style="height:350px;width:100%;"></div>
            </div>
        </div>
        
        <div class="card">
            <div class="card-title">
                学生成绩列表
                <span style="float:right;font-size:0.9rem;font-weight:normal;">
                    <input type="text" id="student-search" placeholder="搜索学生..." style="padding:0.5rem;border:1px solid #e0e0e0;border-radius:4px;margin-right:0.5rem;width:200px;">
                    <button class="btn btn-primary" onclick="exportStudentData()" style="padding:0.5rem 1rem;font-size:0.85rem;">导出Excel</button>
                </span>
            </div>
            <div style="max-height:500px;overflow-y:auto;">
                <table class="students-table" id="students-table">
                    <thead>
                        <tr>
                            <th>学号</th>
                            <th>姓名</th>
                            <th>总成绩</th>
                            <th>平时成绩</th>
                            <th>考试成绩</th>
                            <th>出勤率</th>
                            <th>等级</th>
                            <th>状态</th>
                        </tr>
                    </thead>
                    <tbody id="students-table-body">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.min.js"></script>
<script>
    let currentTeacherId = null;
    let selectedCourseId = null;
    
    async function loadDashboard() {
        try {
            const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
            currentTeacherId = userInfo.id;
            
            if (!currentTeacherId) {
                window.location.href = '/login';
                return;
            }
            
            // 加载教师所授课程
            await loadTeacherCourses();
            
            document.getElementById('loading').style.display = 'none';
            document.getElementById('dashboard-content').style.display = 'block';
            
        } catch (error) {
            showAlert('加载失败: ' + error.message, 'error');
        }
    }
    
    async function loadTeacherCourses() {
        try {
            const data = await apiRequest(`/teachers/${currentTeacherId}/courses`);
            
            if (data.success) {
                const courses = data.data;
                const container = document.getElementById('courses-grid');
                
                if (courses.length === 0) {
                    container.innerHTML = '<p style="color:#7f8c8d;">暂无授课课程</p>';
                    return;
                }
                
                // 为每门课程加载统计信息
                const coursesWithStats = await Promise.all(
                    courses.map(async (course) => {
                        try {
                            const statsData = await apiRequest(`/analytics/courses/${course.id}/statistics`);
                            return {
                                ...course,
                                stats: statsData.success ? statsData.data.statistics : null
                            };
                        } catch (error) {
                            return { ...course, stats: null };
                        }
                    })
                );
                
                container.innerHTML = coursesWithStats.map(course => `
                    <div class="course-card" onclick="showCourseDetails(${course.id})">
                        <h3>${course.name}</h3>
                        <div class="course-code">${course.code} | ${course.semester || '未指定学期'}</div>
                        ${course.stats ? `
                            <div class="course-stats">
                                <div class="stat-item">
                                    <div class="label">选课人数</div>
                                    <div class="value">${course.stats.total_enrolled || 0}</div>
                                </div>
                                <div class="stat-item ${course.stats.average_score >= 75 ? 'success' : ''}">
                                    <div class="label">平均分</div>
                                    <div class="value">${course.stats.average_score ? course.stats.average_score.toFixed(1) : '-'}</div>
                                </div>
                                <div class="stat-item ${course.stats.pass_rate >= 80 ? 'success' : 'danger'}">
                                    <div class="label">及格率</div>
                                    <div class="value">${course.stats.pass_rate ? course.stats.pass_rate.toFixed(1) : '-'}%</div>
                                </div>
                                <div class="stat-item">
                                    <div class="label">完成人数</div>
                                    <div class="value">${course.stats.completed || 0}</div>
                                </div>
                            </div>
                        ` : '<p style="color:#7f8c8d;font-size:0.9rem;">暂无统计数据</p>'}
                    </div>
                `).join('');
            }
        } catch (error) {
            console.error('加载课程失败:', error);
        }
    }
    
    async function showCourseDetails(courseId) {
        selectedCourseId = courseId;
        
        try {
            // 显示详情区域
            document.getElementById('course-details').style.display = 'block';
            
            // 加载成绩分布
            await loadGradeDistribution(courseId);
            
            // 加载学生列表
            await loadStudentsList(courseId);
            
            // 滚动到详情区域
            document.getElementById('course-details').scrollIntoView({ behavior: 'smooth' });
            
        } catch (error) {
            showAlert('加载课程详情失败: ' + error.message, 'error');
        }
    }
    
    async function loadGradeDistribution(courseId) {
        try {
            const data = await apiRequest(`/analytics/courses/${courseId}/grade_distribution`);
            
            if (data.success) {
                const distribution = data.data.distribution;
                const labels = Object.keys(distribution);
                const values = Object.values(distribution);
                
                // 获取DOM元素
                const chartDom = document.getElementById('grade-distribution-chart');
                
                // 销毁旧的图表实例（如果存在）
                const existingChart = echarts.getInstanceByDom(chartDom);
                if (existingChart) {
                    existingChart.dispose();
                }
                
                // 创建新的图表实例
                const chart = echarts.init(chartDom);
                chart.setOption({
                    title: {
                        text: data.data.course_name,
                        subtext: `平均分: ${data.data.statistics.mean.toFixed(1)} | 及格率: ${(100 - data.data.statistics.fail_rate).toFixed(1)}%`,
                        left: 'center',
                        top: 10,
                        subtextStyle: { color: '#7f8c8d' }
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    grid: {
                        top: 90,
                        left: '10%',
                        right: '4%',
                        bottom: '20%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: labels,
                        axisLabel: {
                            interval: 0,
                            rotate: 45,
                            fontSize: 11
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '人数',
                        nameLocation: 'middle',
                        nameGap: 45,
                        nameTextStyle: { color: '#7f8c8d' },
                        max: function(value) { return Math.ceil(value.max * 1.15); }
                    },
                    series: [{
                        data: values,
                        type: 'bar',
                        itemStyle: {
                            color: function(params) {
                                const colors = ['#e74c3c', '#f39c12', '#3498db', '#2ecc71', '#27ae60'];
                                return colors[params.dataIndex];
                            }
                        },
                        label: {
                            show: true,
                            position: 'top',
                            distance: 8
                        }
                    }]
                });
            }
        } catch (error) {
            console.error('加载成绩分布失败:', error);
        }
    }
    
    async function loadStudentsList(courseId) {
        try {
            const tbody = document.getElementById('students-table-body');
            tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;"><div class="spinner"></div></td></tr>';
            
            // 使用真实API获取课程学生列表
            const data = await apiRequest(`/courses/${courseId}/students`);
            
            if (data.success) {
                const students = data.data.students;
                
                if (students.length === 0) {
                    tbody.innerHTML = '<tr><td colspan="7" style="text-align:center;color:#7f8c8d;">暂无学生数据</td></tr>';
                    return;
                }
                
                // 识别风险学生
                const riskStudents = students.filter(s => 
                    (s.score && s.score < 60) || 
                    (s.attendance_rate && s.attendance_rate < 70)
                );
                
                // 显示风险学生预警（紧凑版）
                if (riskStudents.length > 0) {
                    document.getElementById('risk-students-card').style.display = 'block';
                    document.getElementById('risk-count').textContent = riskStudents.length;
                    
                    // 紧凑摘要（只显示前3个）
                    const topRisk = riskStudents.slice(0, 3);
                    document.getElementById('risk-students-summary').innerHTML = `
                        <div style="display:flex;gap:1rem;flex-wrap:wrap;">
                            ${topRisk.map(s => `
                                <div style="background:white;padding:0.75rem;border-radius:4px;border-left:3px solid #e74c3c;flex:1;min-width:200px;">
                                    <strong style="color:#2c3e50;">${s.last_name}${s.first_name}</strong>
                                    <div style="font-size:0.85rem;color:#7f8c8d;margin-top:0.25rem;">${s.student_id}</div>
                                    <div style="font-size:0.85rem;color:#e74c3c;margin-top:0.25rem;">
                                        ${s.score < 60 ? `成绩: ${s.score.toFixed(1)}分 ` : ''}
                                        ${s.attendance_rate < 70 ? `出勤率: ${s.attendance_rate.toFixed(1)}% ` : ''}
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                        ${riskStudents.length > 3 ? `<div style="text-align:center;margin-top:0.5rem;color:#7f8c8d;font-size:0.85rem;">还有 ${riskStudents.length - 3} 名学生...</div>` : ''}
                    `;
                    
                    // 详细列表（默认隐藏）
                    document.getElementById('risk-students-details').innerHTML = `
                        <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:0.75rem;">
                            ${riskStudents.map(s => `
                                <div style="background:white;padding:0.75rem;border-radius:4px;border-left:3px solid #e74c3c;">
                                    <div style="display:flex;justify-content:space-between;align-items:center;">
                                        <strong style="color:#2c3e50;">${s.last_name}${s.first_name}</strong>
                                        <span style="font-size:0.8rem;color:#7f8c8d;">${s.student_id}</span>
                                    </div>
                                    <div style="font-size:0.85rem;color:#e74c3c;margin-top:0.5rem;">
                                        ${s.score < 60 ? `📉 成绩: ${s.score.toFixed(1)}分` : ''}
                                        ${s.score < 60 && s.attendance_rate < 70 ? '<br>' : ''}
                                        ${s.attendance_rate < 70 ? `📅 出勤: ${s.attendance_rate.toFixed(1)}%` : ''}
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    `;
                } else {
                    document.getElementById('risk-students-card').style.display = 'none';
                }
                
                // 分析出勤率与成绩关系
                const studentsWithAttendance = students.filter(s => 
                    s.score && s.attendance_rate
                );
                
                if (studentsWithAttendance.length > 5) {
                    showAttendanceCorrelation(studentsWithAttendance);
                }
                
                // 渲染学生列表
                tbody.innerHTML = students.map(student => {
                    const isFailing = student.score && student.score < 60;
                    const lowAttendance = student.attendance_rate && student.attendance_rate < 70;
                    const rowClass = (isFailing || lowAttendance) ? 'style="background:#fee;"' : '';
                    
                    return `
                        <tr ${rowClass}>
                            <td>${student.student_id || '-'}</td>
                            <td>
                                ${student.last_name || ''}${student.first_name || ''}
                                ${(isFailing || lowAttendance) ? '<span style="color:#e74c3c;">⚠️</span>' : ''}
                            </td>
                            <td>
                                <strong style="color:${getScoreColor(student.score)}">
                                    ${student.score ? student.score.toFixed(2) : '-'}
                                </strong>
                            </td>
                            <td>${student.midterm_score ? student.midterm_score.toFixed(2) : '-'}</td>
                            <td>${student.final_score ? student.final_score.toFixed(2) : '-'}</td>
                            <td>
                                <span style="color:${getAttendanceColor(student.attendance_rate)}">
                                    ${student.attendance_rate ? student.attendance_rate.toFixed(1) + '%' : '-'}
                                </span>
                            </td>
                            <td>
                                <span class="badge badge-${getGradeBadgeClass(student.letter_grade)}">
                                    ${student.letter_grade || '-'}
                                </span>
                            </td>
                            <td>
                                <span class="badge badge-${getStatusBadgeClass(student.status)}">
                                    ${getStatusText(student.status)}
                                </span>
                            </td>
                        </tr>
                    `;
                }).join('');
            }
            
        } catch (error) {
            console.error('加载学生列表失败:', error);
            const tbody = document.getElementById('students-table-body');
            tbody.innerHTML = `<tr><td colspan="7" style="text-align:center;color:#e74c3c;">加载失败: ${error.message}</td></tr>`;
        }
    }
    
    function getScoreColor(score) {
        if (!score) return '#7f8c8d';
        if (score >= 90) return '#27ae60';
        if (score >= 80) return '#2ecc71';
        if (score >= 70) return '#3498db';
        if (score >= 60) return '#f39c12';
        return '#e74c3c';
    }
    
    function getGradeBadgeClass(grade) {
        if (!grade) return '';
        if (grade === 'A' || grade === 'B') return 'success';
        if (grade === 'C' || grade === 'D') return 'warning';
        return 'danger';
    }
    
    function getStatusBadgeClass(status) {
        if (status === 'completed') return 'success';
        if (status === 'enrolled') return 'warning';
        return 'danger';
    }
    
    function getStatusText(status) {
        const statusMap = {
            'enrolled': '在读',
            'completed': '已完成',
            'dropped': '已退课'
        };
        return statusMap[status] || status;
    }
    
    function getAttendanceColor(rate) {
        if (!rate) return '#7f8c8d';
        if (rate >= 90) return '#27ae60';
        if (rate >= 80) return '#2ecc71';
        if (rate >= 70) return '#f39c12';
        return '#e74c3c';
    }
    
    function showAttendanceCorrelation(students) {
        try {
            document.getElementById('attendance-card').style.display = 'block';
            
            // 准备散点图数据
            const scatterData = students.map(s => [
                s.attendance_rate,
                s.score
            ]);
            
            // 获取DOM元素
            const chartDom = document.getElementById('attendance-chart');
            
            // 销毁旧的图表实例（如果存在）
            const existingChart = echarts.getInstanceByDom(chartDom);
            if (existingChart) {
                existingChart.dispose();
            }
            
            // 创建新的图表实例
            const chart = echarts.init(chartDom);
            chart.setOption({
                title: {
                    text: '出勤率与成绩相关性分析',
                    textStyle: {
                        fontSize: 14,
                        color: '#7f8c8d'
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        return `出勤率: ${params.value[0].toFixed(1)}%<br/>成绩: ${params.value[1].toFixed(1)}分`;
                    }
                },
                grid: {
                    left: '10%',
                    right: '10%',
                    bottom: '15%',
                    top: '15%',
                    containLabel: true
                },
                xAxis: {
                    name: '出勤率(%)',
                    nameLocation: 'middle',
                    nameGap: 30,
                    min: 0,
                    max: 100,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                yAxis: {
                    name: '成绩',
                    nameLocation: 'middle',
                    nameGap: 40,
                    min: 0,
                    max: 100,
                    splitLine: {
                        lineStyle: {
                            type: 'dashed'
                        }
                    }
                },
                series: [{
                    type: 'scatter',
                    data: scatterData,
                    symbolSize: 12,
                    itemStyle: {
                        color: '#3498db',
                        opacity: 0.7
                    },
                    markLine: {
                        lineStyle: {
                            type: 'solid',
                            color: '#e74c3c'
                        },
                        data: [
                            {yAxis: 60, label: {formatter: '及格线'}},
                            {xAxis: 70, label: {formatter: '出勤预警线'}}
                        ]
                    }
                }]
            });
            
            window.addEventListener('resize', () => chart.resize());
            setTimeout(() => chart.resize(), 0);
            
        } catch (error) {
            console.error('出勤率分析失败:', error);
        }
    }
    
    let allStudentsData = [];
    
    function exportStudentData() {
        showAlert('Excel导出功能开发中，您可以使用浏览器的打印功能（Ctrl+P）保存为PDF', 'info');
        // TODO: 实现CSV导出功能
    }
    
    function toggleRiskDetails() {
        const details = document.getElementById('risk-students-details');
        const btn = document.getElementById('toggle-risk-btn');
        
        if (details.style.display === 'none') {
            details.style.display = 'block';
            btn.textContent = '收起';
        } else {
            details.style.display = 'none';
            btn.textContent = '展开';
        }
    }
    
    // 学生搜索功能
    document.addEventListener('DOMContentLoaded', function() {
        const searchInput = document.getElementById('student-search');
        if (searchInput) {
            searchInput.addEventListener('input', function(e) {
                const keyword = e.target.value.toLowerCase();
                const tbody = document.getElementById('students-table-body');
                const rows = tbody.querySelectorAll('tr');
                
                rows.forEach(row => {
                    const text = row.textContent.toLowerCase();
                    if (text.includes(keyword)) {
                        row.style.display = '';
                    } else {
                        row.style.display = 'none';
                    }
                });
            });
        }
    });
    
    // 页面加载时执行
    window.addEventListener('DOMContentLoaded', loadDashboard);
</script>
{% endblock %}




